package com.example.myapplication.storage;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.myapplication.R;

public class SharedPreferencesStorageActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText etName;
    private EditText etAge;
    private EditText etHeight;
    private EditText etWeight;
    private CheckBox cbMarried;

    private SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_shared_preferences_storage);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        etName = findViewById(R.id.et_name);
        etAge = findViewById(R.id.et_age);
        etHeight = findViewById(R.id.et_height);
        etWeight = findViewById(R.id.et_weight);
        cbMarried = findViewById(R.id.cb_married);

        findViewById(R.id.btn_save).setOnClickListener(this);

        sharedPreferences = getSharedPreferences("config", Context.MODE_PRIVATE);

        etName.setText(sharedPreferences.getString("name", null));
        etAge.setText(sharedPreferences.getString("age", null));
        etHeight.setText(sharedPreferences.getString("height", null));
        etWeight.setText(sharedPreferences.getString("weight", null));
        if (sharedPreferences.getBoolean("married", false)) {
            cbMarried.setChecked(true);
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_save) {
            // 保存到SharedPreferences
            SharedPreferences.Editor edit = sharedPreferences.edit();
            edit.putString("name", etName.getText().toString());
            edit.putString("age", etAge.getText().toString());
            edit.putString("height", etHeight.getText().toString());
            edit.putString("weight", etWeight.getText().toString());
            edit.putBoolean("married", cbMarried.isChecked());
            edit.apply();
        }
    }
}